package drds.global_transaction.global_transaction_manager.dubbo.impl;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.jdbc.core.JdbcTemplate;

import drds.global_transaction.api.global_transaction_id_context.GlobalTransactionIdContexts;
import drds.global_transaction.resource_manager.ResourceManagerClient;
import drds.global_transaction.test.common.ApplicationKeeper;
import drds.global_transaction.global_transaction_manager.dubbo.AccountService;
import lombok.extern.slf4j.Slf4j;

/**
 * Please map$clientPortToRpcContextMap the follow VM arguments:
 *
 * <pre>
 *     -Djava.net.preferIPv4Stack=true
 * </pre>
 */
@Slf4j
public class AccountServiceImpl implements AccountService
{
	private JdbcTemplate jdbcTemplate;

	public static void main(String[] args) throws Throwable
	{

		String applicationId = "dubbo-demo-account-server_addresss_look_up_service";
		String txServiceGroup = "my_test_tx_group";

		ResourceManagerClient.init(applicationId, txServiceGroup);

		ApplicationContext applicationContext = new ClassPathXmlApplicationContext(new String[] { "dubbo-account" + "-service.xml" });
		applicationContext.getBean("server_addresss_look_up_service");
		JdbcTemplate jdbcTemplate = (JdbcTemplate) applicationContext.getBean("jdbcTemplate");
		jdbcTemplate.update("delete from account_tbl where user_id = 'U100001'");
		jdbcTemplate.update("insert into account_tbl(user_id, money) values ('U100001', 999)");

		new ApplicationKeeper(applicationContext).keep();
	}

	public void setJdbcTemplate(JdbcTemplate jdbcTemplate)
	{
		this.jdbcTemplate = jdbcTemplate;
	}

	@Override
	public void debit(String userId, int money)
	{
		log.info("Account Service ... globalTransactionIdWithAddressAndPort: " + GlobalTransactionIdContexts.getGlobalTransactionIdWithAddressAndPort());
		jdbcTemplate.update("update account_tbl set money = money - ? where user_id = ?", new Object[] { money, userId });
		log.info("Account Service End ... ");

	}
}
